//
//  ReleaseController.m
//  PianoAndPoemDirectSeeding
//
//  Created by 梅津山 on 2017/7/7.
//  Copyright © 2017年 梅津山. All rights reserved.
//

#import "ReleaseController.h"
#import "GetPhotoTools.h"
#import "AddImageCell.h"
//#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "ImageDeleteView.h"

#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height


@interface ReleaseController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UITextView *dataTextV;

@property (weak, nonatomic) IBOutlet UICollectionView *imageCollectionV;

@property (weak, nonatomic) IBOutlet UITextField *faultLocationL;

@property (weak, nonatomic) IBOutlet UIButton *slightBtn;

@property (weak, nonatomic) IBOutlet UIButton *mediumBtn;

@property (weak, nonatomic) IBOutlet UIButton *seriousBtn;

@property (nonatomic, strong) UILabel *placeHolderLabel;

@property (nonatomic, strong) UIButton *seleterBtn;

@property (nonatomic, assign) int num;

@property (nonatomic, strong) NSMutableArray<UIImage *> *imageArr;

@property (nonatomic, assign)  NSString *state;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionHeight;

@property (nonatomic, strong) ImageDeleteView *homeV;

@property (nonatomic, strong) UIImage *imageT;
@end

@implementation ReleaseController
- (void)viewDidLoad {
    [super viewDidLoad];
    _state = @"未维修";
    _imageCollectionV.delegate = self;
    _imageCollectionV.dataSource = self;
    _num = 1;
    _imageArr = [NSMutableArray array];
    //textView的提醒字符
    UIBarButtonItem *releaseItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClicked)];
    self.navigationItem.rightBarButtonItem = releaseItem;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBtnClicked)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.dataTextV.delegate = self;
    self.placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(2,0,343,30)];
    self.placeHolderLabel.numberOfLines = 0;
    self.placeHolderLabel.text = @"描述故障详情，比如：所在位置，破损情况";
    self.placeHolderLabel.font = [UIFont systemFontOfSize:10];
    self.placeHolderLabel.textColor = [UIColor darkGrayColor];
    self.placeHolderLabel.backgroundColor =[UIColor clearColor];
    [self.dataTextV addSubview:self.placeHolderLabel];
    
    //按钮的边框及圆角
    self.slightBtn.layer.borderWidth = 1;
    self.slightBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.slightBtn.layer.cornerRadius = 10;
    self.slightBtn.layer.masksToBounds = YES;
    self.mediumBtn.layer.borderWidth = 1;
    self.mediumBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.mediumBtn.layer.cornerRadius = 10;
    self.mediumBtn.layer.masksToBounds = YES;
    self.seriousBtn.layer.borderWidth = 1;
    self.seriousBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.seriousBtn.layer.cornerRadius = 10;
    self.seriousBtn.layer.masksToBounds = YES;
    
}

- (void)textViewDidChange:(UITextView*)textView{
    if([textView.text length] == 0){
        self.placeHolderLabel.text = @"描述故障详情，比如：所在位置，破损情况";
    }else{
        self.placeHolderLabel.text = @"";//这里给空
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _num;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    AddImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddImageCell" forIndexPath:indexPath];
    if (self.imageArr.count == 9) {
        UIImage *image = self.imageArr[indexPath.row];
        cell.image = image;
    }else{
        if (indexPath.row != (_num - 1)) {
            UIImage *image = self.imageArr[indexPath.row];
            cell.image = image;
        }else{
            cell.image = [UIImage imageNamed:@"发布图片+"];
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.imageArr.count == 9) {
        _homeV =[ImageDeleteView sharedRect:self.view.frame];
        [_homeV tapActionImage:_imageArr[indexPath.row]];
        _homeV.navigBlock = ^{
            [super.navigationController setNavigationBarHidden:NO animated:YES];
        };
        //点击删除时的block删除
        __weak typeof(self) weakSelf = self;
        _homeV.deleteBlock = ^{
            weakSelf.num --;
            [weakSelf.imageArr removeObjectAtIndex:indexPath.row];
            [weakSelf.imageCollectionV reloadData];
        };

        [super.navigationController setNavigationBarHidden:YES animated:YES];
        [self.view addSubview:_homeV];
    }else{
        if (indexPath.row == (_num - 1)) {
            GetPhotoTools *tools = [GetPhotoTools getPhotoShared];
            [tools alterGetPhoto:self];
            [GetPhotoTools getPhotoShared].imageBlock = ^(UIImage *image) {
                [_imageArr addObject:image];
                if (indexPath.row != 8) {
                    _num ++;
                }
                if (indexPath.row > 2 && indexPath.row < 7) {
                    _collectionHeight.constant = 180;
                }
                if(indexPath.row > 6){
                    _collectionHeight.constant = 260;
                }
                if (indexPath.row < 3) {
                    _collectionHeight.constant = 100;
                }
                [_imageCollectionV reloadData];
            };
        }else{
            [super.navigationController setNavigationBarHidden:YES animated:YES];
            _homeV =[ImageDeleteView sharedRect:self.view.frame];
            //返回时的block调用
            _homeV.navigBlock = ^{
                [super.navigationController setNavigationBarHidden:NO animated:YES];
            };
            __weak typeof(self) weakSelf = self;
            _homeV.deleteBlock = ^{
                weakSelf.num --;
                [weakSelf.imageArr removeObjectAtIndex:indexPath.row];
                [weakSelf.imageCollectionV reloadData];
            };
            [_homeV tapActionImage:_imageArr[indexPath.row]];
            [self.view addSubview:_homeV];
        }
    }
}

//返回
- (void)leftBtnClicked{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//发布
- (void)rightBtnClicked{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AVUser *user = [AVUser currentUser];
    
//    NSLog(@"%@",user.username);
    // LeanCloud - 构建图片
    // owner 字段为 Pointer 类型，指向 _User 表
    NSMutableArray *fileArr = [NSMutableArray arrayWithCapacity:self.imageArr.count];
    for (UIImage *image in self.imageArr) {
        NSData *data = UIImagePNGRepresentation(image);
        AVFile *file = [AVFile fileWithData:data];
        [fileArr addObject:file];
    }
//    UIImage *img = self.imageArr.currentBackgroundImage;
    AVObject *todoFolder = [[AVObject alloc] initWithClassName:@"Content"];// 构建对象
    /******/
    [todoFolder setObject:user forKey:@"owner"];
    [todoFolder setObject:_dataTextV.text forKey:@"particulars"];// 设置名称
    [todoFolder setObject:_faultLocationL.text forKey:@"location"];// 设置名称
    [todoFolder setObject:_state forKey:@"state"];
    
    
    NSString *flag = nil;
    if (self.slightBtn.selected) {
        flag = @"1";
    }else if (self.mediumBtn.selected) {
        flag = @"2";
    }else if (self.seriousBtn.selected){
        flag = @"3";
    }else {
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"请选择故障等级" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alter animated:YES completion:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alter dismissViewControllerAnimated:YES completion:nil];
            });
        }];
    }
    
    [todoFolder setObject:flag forKey:@"grade"];// 设置名称
    [todoFolder setObject:fileArr forKey:@"imageArr"];// 设置名称
    [todoFolder saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
         [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (succeeded) {
            // 请求成功
            UIAlertController *aletv = [UIAlertController alertControllerWithTitle:@"" message:@"发布成功" preferredStyle:    UIAlertControllerStyleAlert];
            
            [self presentViewController:aletv animated:YES completion:^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [aletv dismissViewControllerAnimated:YES completion:^{
                        [self leftBtnClicked];
                    }];
                });
            }];

        } else {
            NSLog(@"%@",error);
            UIAlertController *aletv = [UIAlertController alertControllerWithTitle:@"" message:@"发布失败" preferredStyle:    UIAlertControllerStyleAlert];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [aletv dismissViewControllerAnimated:YES completion:nil];
            });
            [self presentViewController:aletv animated:YES completion:^{
               
            }];
        }
    }];
}

- (IBAction)faultLevelBtnClicked:(UIButton *)sender {
    _seleterBtn.selected = NO;
    _seleterBtn.backgroundColor = [UIColor whiteColor];
    sender.selected = YES;
    _seleterBtn = sender;
    _seleterBtn.backgroundColor = [UIColor brownColor];
    [_imageCollectionV reloadData];
}



@end
